<?php

namespace App\Http\Controllers;

use App\Models\Course;
use App\Models\CourseRecommend;
use App\Models\User;
use App\Models\UserCollection;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;

class CourseController extends BaseController
{

    public function courseList(Request $request)
    {
        $user = User::getInfoByToken();

        $query = Course::with('teacher.qualifications');
        $recommend = CourseRecommend::all()->pluck('reason', 'course_id')->toArray();
        $collect = UserCollection::where('user_id', $user->id)->pluck('course_id')->toArray();
        if ($request->input('courseType') == 'recommend') {
            $query->whereIn('id', array_keys($recommend));
        }
        if ($request->input('courseType') == 'collect') {
            $query->whereIn('id', $collect);
        }
        $list = $query->orderByDesc('id')->paginate(12);
        $i = 0;
        foreach ($list as &$item) {
            $item->cover = env('APP_URL').'/images/'.Course::$imgs[$i];
            $item->isRecommend = Arr::has($recommend, $item->id);
            $item->recommendReason = Arr::get($recommend, $item->id, '');
            $item->isCollect = in_array($item->id, $collect);
            $i += 1;
        }
        return $this->successResponse($list);
    }

    public function collectCourse(Request $request,UserCollection $collection)
    {
        $user = User::getInfoByToken();
        $collection->insert([
            'user_id' => $user->id,
            'course_id' => $request->input('course_id'),
        ]);
        return $this->successResponse([], '收藏成功');
    }

    public function unCollectCourse(Request $request,UserCollection $collection)
    {
        $user = User::getInfoByToken();
        $collection->where('user_id', $user->id)->where('course_id', $request->input('course_id'))->delete();
        return $this->successResponse([], '取消收藏成功');
    }


}
